package com.sq.partner.manager.controller;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.*;
import com.sq.partner.manager.service.*;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "/fuelGasPolicyList")
public class FuelGasPolicyListController {

    private static Logger logger = LogUtil.getLog(FuelGasPolicyListController.class);

    @Resource
    private IGatewayLifePolicyListService lifePolicyListService;

    @Resource
    private IFuelGasPolicyListService fuelGasPolicyListService;

    @Resource
    private IGatewayChannelInfoConfigService channelInfoConfigService;

    @Resource
    private IGatewayProductService productService;

    @Resource
    private IGatewayCustomerService customerService;

    @Resource
    private INlifeProdConfigService nlifeProdConfigService;



    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model){
        //查询条件中的“产品”仅可选择08开头的财产险产品
        List<DictDto> prodTypeList = DictCache.getProdTypeAndHeadCore("2","08");

        model.addAttribute("prodTypeList", prodTypeList);
        return "transManager/fuelGasPolicyList";
    }

    /**
     * 查询当前用户的权限机构,控制当前登录用户权限只可查询本机构下的保单信息
     * @param session
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryPrivilegeBranch",method = RequestMethod.POST)
    @ResponseBody
    public Result queryPrivilegeBranch(HttpSession session) throws Exception {
        GatewayUser user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
        logger.info("当前登录用户的userCode为"+user.getUserCode()+",DepartmentStr:"+user.getDepartmentStr());

        if(null != user && StrUtil.isNotEmpty(user.getDepartmentStr())){
            return Result.data(lifePolicyListService.queryPrivilegeBranch(user.getDepartmentStr()));
        }

        return Result.fail();
    }

    /**
     * 查询传入机构及其子机构
     * @param size
     * @param pageIndex
     * @param deptCode
     * @param
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryDeptByDeptAndParentDeptCode",method = RequestMethod.POST)
    @ResponseBody
    public Page<CoreDept> queryDeptByDeptAndParentDeptCode(Integer size, Integer pageIndex,
                                                           String deptCode, String deptCname, String parentDeptCode) throws Exception{
        if(StrUtil.isEmpty(parentDeptCode)){
            throw new AppException("机构不能为空");
        }

        Page<CoreDept> page=new Page<CoreDept>();
        page.setCurrent(pageIndex);
        page.setSize(size);
        CoreDept dept=new CoreDept();
        dept.setDeptCode(deptCode);
        dept.setDeptCname(deptCname);
        page.setType(dept);

        return lifePolicyListService.queryDeptPageByDeptAndParentDeptCode(page, parentDeptCode);
    }

    /**
     * 查询人险相关合作伙伴
     * @param
     * @return List<GatewayChannelInfo>
     * @throws Exception
     */
    @RequestMapping(value = "/queryChannelInfoOfLife",method = RequestMethod.POST)
    public @ResponseBody Page<GatewayChannelInfo> queryChannelInfoOfLife(Integer size, Integer pageIndex,
                                                                         String parentDeptCode, String channelName, String channelCode) throws Exception{
        if(StrUtil.isEmpty(parentDeptCode)){
            throw new AppException("机构不能为空");
        }

        Page<GatewayChannelInfo> page = new Page<GatewayChannelInfo>();
        page.setCurrent(pageIndex);
        page.setSize(size);

        GatewayChannelInfo channelInfo = new GatewayChannelInfo();
        channelInfo.setDeptCode(parentDeptCode);
        channelInfo.setChannelCode(channelCode);
        channelInfo.setChannelName(channelName);
        page.setType(channelInfo);
        return lifePolicyListService.queryChannelInfoPageOfLife(page);
    }

    /**
     * 查询人险相关合作伙伴
     * @param
     * @return List<GatewayChannelInfo>
     * @throws Exception
     */
    @RequestMapping(value = "/querySubChannelTree",method = RequestMethod.POST)
    @ResponseBody
    public List<TreeDto> querySubChannelTree(String parentChannelCode) throws Exception{
        if(StrUtil.isEmpty(parentChannelCode)){
            throw new AppException("合作伙伴代码不能为空");
        }

        return lifePolicyListService.querySubChannelTreeByParentChannelCode(parentChannelCode);
    }

    /**
     * 分页条件查询财险保单
     * @param session
     * @param pageIndex
     * @param policy
     * @param privilegeBranch
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryFuelGasPolicyListPageByCriteria")
    @ResponseBody
    public Page queryFuelGasPolicyPageByCriteria(HttpSession session, Integer pageIndex,
                                               GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
                                               String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception {

        @SuppressWarnings("rawtypes")
        Page page = beforeQueryFuelGasPolicyPageByCriteria(session, pageIndex, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);
        if("error".equals(page.getResult()) || "noChannelInfo".equals(page.getResult())){
            return page;
        }
        return fuelGasPolicyListService.queryFuelGasPolicyPageByCriteria(page);
    }
    /**
     * 汇总展示
     * @param session
     * @param pageIndex
     * @param policy
     * @param privilegeBranch
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryFuelGasPolicyAll")
    @ResponseBody
    public Map<String,Object> queryFuelGasPolicyAll(HttpSession session, Integer pageIndex,
                                                  GatewayPolicy policy, String privilegeBranch, String polSubDateBegin,
                                                  String polSubDateEnd, String polBeginDateBegin, String polBeginDateEnd, String tbrName, String tbrId, String bbrName) throws Exception {

        @SuppressWarnings("rawtypes")
        Page page = beforeQueryFuelGasPolicyPageByCriteria(session, pageIndex, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);
        Map<String,String> map = (Map<String, String>) page.getType();
        return fuelGasPolicyListService.queryFuelGasPolicyAll(map);
    }

    /**
     * 下载财险保单信息
     * @param session
     * @param response
     * @param policy
     * @param privilegeBranch
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @throws Exception
     */
    @RequestMapping(value = "/downloadFuelGasPolicyFileByCriteria")
    public void downloadFuelGasPolicyFileByCriteria(HttpSession session, HttpServletResponse response,
                                                  GatewayPolicy policy, String privilegeBranch, String polSubDateBegin,
                                                  String polSubDateEnd, String polBeginDateBegin, String polBeginDateEnd, String tbrName, String tbrId, String bbrName) throws Exception {

        Page page = beforeQueryFuelGasPolicyPageByCriteria(session, -1, policy, privilegeBranch,polSubDateBegin, polSubDateEnd, polBeginDateBegin, polBeginDateEnd,tbrName,tbrId,bbrName);

        Map<String,Object> map = (Map<String, Object>) page.getType();
        List<Map<String, Object>> nocarPolicyList = fuelGasPolicyListService.queryFuelGasPolicyListByCriteria(map);
        fuelGasPolicyListService.downloadFuelGasPolicyFile(nocarPolicyList, response);
    }


    /**
     * 财险保单查询和保单信息下载前进行验证
     * @param session
     * @param pageIndex
     * @param policy
     * @param privilegeBranch
     * @param polSubDateBegin
     * @param polSubDateEnd
     * @param polBeginDateBegin
     * @param polBeginDateEnd
     * @return
     * @throws Exception
     */
    public Page beforeQueryFuelGasPolicyPageByCriteria(HttpSession session, Integer pageIndex,
                                                     GatewayPolicy policy,String privilegeBranch,String polSubDateBegin,
                                                     String polSubDateEnd,String polBeginDateBegin,String polBeginDateEnd,String tbrName,String tbrId,String bbrName) throws Exception{
//		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);

        Page page = new Page();
        Map<String,Object> map = new HashMap<String, Object>();
        if(pageIndex != -1){
            page.setCurrent(pageIndex);
            map = SqlUtil.buildPageMap(page);
        }

//		String dptCode = policy.getDptCde();
        String dptCodeStr = "";

        //机构验证
        if(StrUtil.isEmpty(privilegeBranch)){
            throw new AppException("系统异常：机构不能为空");
        }else{
            if(!(channelInfoConfigService.checkIsHasPrivilege(session, privilegeBranch))){
                throw new AppException("用户权限不足");
            }
        }
        map.put("privilegeBranch",privilegeBranch);

        map.put("dptCode", policy.getDptCde());

	/*	String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		if(StrUtil.isEmpty(polSubDateBegin) && StrUtil.isEmpty(polSubDateEnd)&& StrUtil.isEmpty(policy.getPolno())){
			page.setResult("error");
			page.setMessage("查询时保单号或保单提交日期必填其一");
			return page;
		}else if(StrUtil.isEmpty(polSubDateBegin) && StrUtil.isNotEmpty(polSubDateEnd)){
			polSubDateBegin = getAssignedDateStr(polSubDateEnd, 3);
		}else if(StrUtil.isNotEmpty(polSubDateBegin) && StrUtil.isEmpty(polSubDateEnd)){
			polSubDateEnd = getAssignedDateStr(polSubDateBegin, -3);
		}else if(StrUtil.isNotEmpty(polSubDateBegin) && StrUtil.isNotEmpty(polSubDateEnd)){
			//判断起止日期跨度是否超过3个月，超过true
			if(if2DateIntervalOverAssignedMonth(polSubDateBegin, polSubDateEnd, 3)){
				page.setResult("error");
				page.setMessage("保单提交日期跨度不能超过3个月");
				return page;
			}
		}*/

        //保单提交日期
        if(StrUtil.isNotEmpty(polSubDateBegin)){
            polSubDateBegin = polSubDateBegin + "00:00:00";
        }
        if(StrUtil.isNotEmpty(polSubDateEnd)){
            polSubDateEnd = polSubDateEnd + "23:59:59";
        }

        map.put("polSubDateBegin", polSubDateBegin);
        map.put("polSubDateEnd", polSubDateEnd);

        //保单生效日期
        if(StrUtil.isNotEmpty(polBeginDateBegin)){
            polBeginDateBegin = polBeginDateBegin + " 00:00:00";
        }
        if(StrUtil.isNotEmpty(polBeginDateEnd)){
            polBeginDateEnd = polBeginDateEnd + " 23:59:59";
        }

        map.put("polBeginDateBegin", polBeginDateBegin);
        map.put("polBeginDateEnd", polBeginDateEnd);


        //合作伙伴代码
        GatewayChannelInfo channelInfo = new GatewayChannelInfo();
        channelInfo.setDeptCode(privilegeBranch);
        List<Map> channelInfoList = fuelGasPolicyListService.queryChannelListOfNocar(channelInfo,"nocar");
        if(null == channelInfoList || channelInfoList.size() == 0){
            page.setResult("noChannelInfo");
            return page;
        }

        String channelCodeStr;
        if(StrUtil.isEmpty(policy.getPartnerNo())){
            channelCodeStr = "";
        }else{
            List<String> channelCodeList = new ArrayList<String>();
            for (Map m : channelInfoList) {
                channelCodeList.add(m.get("CHANNELCODE").toString());
            }
            if(!channelCodeList.contains(policy.getPartnerNo())){
                page.setResult("error");
                page.setMessage("合作伙伴["+policy.getPartnerNo()+"]没有权限执行此操作");
                return page;
            }
            channelCodeStr="'"+policy.getPartnerNo()+"'";
        }
        map.put("channelCodeStr", channelCodeStr);
        map.put("isHq", 'N');
        //合作伙伴子机构
        if(StrUtil.isNotEmpty(policy.getPartnerSubCode()) && StrUtil.isEmpty(policy.getPartnerNo())){
            page.setResult("error");
            page.setMessage("合作伙伴子机构不为空，合作伙伴不允许为空");
            return page;
        }
        if("00".equals(privilegeBranch)){
            map.put("isHq", 'Y');
        }else {
            map.put("isHq", 'N');
        }
        map.put("partnerSubCode", policy.getPartnerSubCode());

        map.put("polno", policy.getPolno());
        map.put("stateId", policy.getStateId());
        map.put("orderId", policy.getOrderId());
        map.put("tradProdType", policy.getTradProdType());
        map.put("spical1", policy.getSpical1());
        map.put("tbrName", tbrName);
        map.put("tbrId", tbrId);
        map.put("bbrName", bbrName);
        page.setType(map);
        return page;
    }


    //转换成sql  in 字符串（格式为 'a','b','c'）
    public String transList2InStr(List<String> list){
        StringBuffer sb = new StringBuffer("'");
//		if(null == list && list.size() == 0){
        if(null == list || list.size() == 0){
            return "''";
        }
        for (String string : list) {
            sb.append(string+"','");
        }

        return sb.substring(0, sb.length()-2);
    }


    /**
     * 根据传入的日期字符串("yyyy-MM-dd")，得到该日期之前assignedMonth个月份的日期字符串（assignedMonth为负数时指之后月份的日期字符串）
     * @param dateStr
     * @param assignedMonth
     * @return
     * @throws Exception
     */
    public String getAssignedDateStr(String dateStr,int assignedMonth) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            logger.info("日期格式不正确",e);
            throw new AppException("日期格式不正确");
        }

        date.setMonth(date.getMonth() - assignedMonth);

        return sdf.format(date);
    }

    /**
     * 判断两个时间间隔是否超过指定月份(超过返回true)--传入字符串格式（yyyy-MM-dd）
     * @param dateBeginStr
     * @param dateEndStr
     * @param assignedMonth
     * @return
     * @throws AppException
     */
    public boolean if2DateIntervalOverAssignedMonth(String dateBeginStr,String dateEndStr,int assignedMonth) throws AppException{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dateBegin;
        Date dateEnd;
        try {
            dateBegin = sdf.parse(dateBeginStr);
            dateEnd = sdf.parse(dateEndStr);
        } catch (ParseException e) {
            logger.info("日期格式不正确",e);
            throw new AppException("日期格式不正确");
        }

        dateBegin.setMonth(dateBegin.getMonth() + assignedMonth);

        return !dateBegin.after(dateEnd);
    }

    //added by gzz@20151105 for shen zhen you hua begin
    @RequestMapping(value = "/queryViewDetail", method = RequestMethod.POST)
    @ResponseBody public Page<Map<String, Object>> queryByTradNoticeId(String polNo,String tradProdType) throws Exception {
        Page<Map<String, Object>> page = new Page<Map<String,Object>>();
        if(StrUtil.isEmpty(polNo) /*|| StrUtil.isEmpty(tradProdType)*/){
            page.setResult("error");
            page.setMessage("请求参数错误，请稍后重试！");
            return page;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        // 逻辑处理思路：根据 产品类型进入相应的分支
        //1.根据保单号查询保单的相关信息
        //2.查询投被保人相关信息
        //3.查询受益人信息
        //4.查询险种信息
        GatewayPolicy policyInfo = fuelGasPolicyListService.queryPolicyInfoByPolNo(polNo);//1.
        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
        df.applyPattern("###,###,###,###,###,###.00");
        if(null!=policyInfo && null!=policyInfo.getAmount()){
            policyInfo.setAmountFormatStr(df.format(policyInfo.getAmount()));
        }
        if(null!=policyInfo && null!=policyInfo.getPremium()){
            policyInfo.setPremiumFormatStr(df.format(policyInfo.getPremium()));
        }
        //非即时起保保单保险止期应该是数据库所存日期的24:00:00
        if(null!=policyInfo && null!=policyInfo.getEndDateStr()){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
            String endDateStr = policyInfo.getEndDateStr();
            policyInfo.setEndDateStr(sdf.format(sdf.parse(endDateStr)));
        }
        GatewayNocarBase  gatewayNocarBase=	null;
        /**查询保险人信息*/
        if(null!=policyInfo && StrUtil.isNotEmpty(policyInfo.getPolicyId())){
            gatewayNocarBase=	fuelGasPolicyListService.queryNocarBaseByPolicyId(policyInfo.getPolicyId());

        }
        map.put("gatewayNocarBase", gatewayNocarBase);
        map.put("policy_detail_Info", policyInfo);

        page.setObj(map);
        return page;
    }

    @RequestMapping(value = "/downloadTeamPolicyBBRInfoFileByPolNo",method = RequestMethod.POST)
    public void downloadTeamPolicyBBRInfoFileByPolNo(String polNo,HttpServletResponse response) throws Exception {
        if(StrUtil.isNotEmpty(polNo)){
            lifePolicyListService.downloadLifeTeamPolicyBBRInfoList(polNo, response);
        }else{
            logger.info("非法参数polNo（空值）传入，清单下载保单号不能为空");
        }
    }

    //added by gzz@20151105 for shen zhen you hua end
    @RequestMapping(value = "/reSendEmail", method = RequestMethod.POST)
    @ResponseBody
    public Result reSendEmail(String polNo,String email) throws Exception {
        logger.info("邮件重发： polNo: "+polNo+" 邮箱地址："+email);
        if(StrUtil.isEmpty(polNo)){
            return Result.fail("参数有误");
        }
        if(StrUtil.isEmpty(email)){
            return Result.fail("邮箱不能为空");
        }
        return fuelGasPolicyListService.addEmailReSend(polNo, email);
    }

    @RequestMapping(value = "/reSendSms", method = RequestMethod.POST)
    @ResponseBody
    public Result reSendSms(String polNo,String phoneNo) throws Exception {
        logger.info("短信重发： polNo: "+polNo+" 邮箱地址："+phoneNo);
        if(StrUtil.isEmpty(polNo)){
            return Result.fail("参数有误");
        }
        if(StrUtil.isEmpty(phoneNo)){
            return Result.fail("手机号不能为空");
        }
        return fuelGasPolicyListService.addSMSReSend(polNo, phoneNo);
    }


}
